package com.kr.weitao.util;


import okhttp3.*;

import java.io.IOException;

/**
 * Created by iBo on 16/4/25.
 */
public class HttpClient {

    OkHttpClient okHttpClient = new OkHttpClient();
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * Http GET 请求
     *
     * @param url
     * @return
     * @throws IOException
     */
    public Response get(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();
        Response response = okHttpClient.newCall(request).execute();
        return response;
    }


    /**
     * Http POST 请求
     *
     * @param
     * @param
     * @return
     * @throws IOException
     */
    public Response post(Request request) throws IOException {
        Response response = okHttpClient.newCall(request).execute();
        return response;
    }

    /**
     * Http POST 请求
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public Response Post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            return response;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * Http DELETE 请求
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public Response delete(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(url).delete(body).build();
        Response response = okHttpClient.newCall(request).execute();
        return response;
    }


    /**
     * Http PUT 请求
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public Response put(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(url).put(body).build();
        Response response = okHttpClient.newCall(request).execute();
        return response;
    }


}
